#include "tcpclientwidget.h"
#include "ui_tcpclientwidget.h"

QTcpSocket* TcpClientWidget:: qTcpSocket=NULL;

TcpClientWidget::TcpClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TcpClientWidget)
{
    ui->setupUi(this);

    qTcpSocket = new QTcpSocket(this);

    ui->textEditShow->setReadOnly(true);
    this->setWindowTitle("客户端");



}

TcpClientWidget::~TcpClientWidget()
{
    delete ui;
}

void TcpClientWidget::on_pushButtonConnect_clicked()
{
    QString ip = ui->lineEditIp->text();
    int port = ui->lineEditPort->text().toInt();
    if (qTcpSocket->isOpen()) {
        QString showText = QString(ip).append(":%1").arg(port);
        ui->textEditShow->append(QString("已连接到服务器：%1了,请先断开连接,再重新链接").arg(showText));
        return;
    }
    qTcpSocket->connectToHost(QHostAddress(ip),port);
    connect(qTcpSocket,&QTcpSocket::connected,
            [=](){

        //文本区域展示链接状态
        QString showText = QString(ip).append(":%1").arg(port);
        if (qTcpSocket->isOpen()) {
            ui->textEditShow->append(QString("已连接到服务器：%1").arg(showText));
        }else {
            ui->textEditShow->append(QString("连接到服务器：%1 未响应！").arg(showText));
        }

    });
    connect(qTcpSocket,&QTcpSocket::readyRead,
            [=](){
        QByteArray qByteArray = qTcpSocket->readAll();
        ui->textEditShow->append(QString("服务端：").append(qByteArray));
    });
}

void TcpClientWidget::on_pushButtonSend_clicked()
{
    QString sendText = ui->textEditSend->toPlainText();
    if (qTcpSocket && qTcpSocket->isOpen()) {
        if ( !sendText.isEmpty()) {
            int writeResult = qTcpSocket->write(sendText.toUtf8().data());
            if (writeResult==-1) {
                ui->textEditShow->append(QString("发生错误,无网络连接,或者服务器已断开连接！"));
                return;
            }
            ui->textEditSend->clear();
        }
    }else {
        ui->textEditShow->append(QString("未连接服务器！"));
    }
}

void TcpClientWidget::on_pushButtonClose_clicked()
{
    if (qTcpSocket->isOpen()) {
        qTcpSocket->disconnect();
        qTcpSocket->close();
        if (qTcpSocket->isOpen()) {
            ui->textEditShow->append(QString("未成功断开服务器！请稍候再试!"));
        }else {
            ui->textEditShow->append(QString("已断开服务器！"));
        }
    }else{
        ui->textEditShow->append(QString("未连接服务器！"));
    }

}
